#!/usr/bin/env python
# -*- coding: utf8 -*-

import re, os, hashlib

PATH_PO = '../_po'
PATH_TRANSLATIONS = '../translations'
TMPL_TR = '# -*- coding: utf8 -*-\nitems = [\n%s]\n'
TMPL_INIT = '# -*- coding: utf8 -*-\n__all__ = [\n%s]\n'

all_resources_str = ''
# all_en_items = []
for i in os.listdir(PATH_PO):
    if i[0] in ['.', '_']: continue
    all_resources_str += '"%s",\n' % i
    resource_dir_po = os.path.join(PATH_PO, i)
    resource_dir_tr = os.path.join(PATH_TRANSLATIONS, i)
    if not os.path.exists(resource_dir_tr):
        os.mkdir(resource_dir_tr)
    all_languages_str = '"en",\n'
    for lang in os.listdir(resource_dir_po):
        if (lang[0] in ['.', '_']) or (lang[-3:] != '.po'): continue
        lang = lang[:-3]
        all_languages_str += '"%s",\n' % lang
        po_path = os.path.join(resource_dir_po, '%s.po' % lang)
        tr_path = os.path.join(resource_dir_tr, '%s.py' % lang)
        
        ##############################################
        data = open(po_path).read()
        en = []
        ru = []
        for i in re.findall(r'^msgid "([^"]+)"\s*msgstr "([^"]*)', data, re.MULTILINE):
#             all_en_items.append(i[0])
            en.append(i[0])
            ru.append(i[1])
        en_str = ''
        for i in en:
            en_str += '"%s",\n' % i
        ru_str = ''
        for i in ru:
            ru_str += '"%s",\n' % i

        open(os.path.join(resource_dir_tr, 'en.py'), 'w').write(TMPL_TR % en_str)
        open(tr_path, 'w').write(TMPL_TR % ru_str)
    open(os.path.join(resource_dir_tr, '__init__.py'), 'w').write(TMPL_INIT % all_languages_str)
# all_en_items_str = '\nkeymap = {\n'
# for k in all_en_items:
#     all_en_items_str += 
open(os.path.join(PATH_TRANSLATIONS, '__init__.py'), 'w').write(TMPL_INIT % all_resources_str)